<script>
import index from "vuex";

export default {
  name: "MainView",
  computed: {
    cartAmount () {
      let amount = 0
      for (let i = 0; i < this.cart.length; i++) {
        amount += this.cart[i].price * this.cart[i].quantity
      }
      return amount
    }
  },
  data(){
    return {
      cart: [],
      cartModal: false,
      allSpData: [],
      personAddr: [],
      selectedAddress: '',
      showModelSelectionModal: false,
      availableModels: [],
      selectedProduct: {},
      selectedModel: null
    }
  },
  methods: {
    goMyOrder(){
      this.$router.push("/order")
    },
    queryAddrs() {
      this.$axios.get(
          "/member/address/list"
      ).then(
          (resp) => {
            this.personAddr = resp.data.data
          }
      ).catch(
          () => {
            alert("获取地址失败")
          }
      )
    },
    showCart(){
      this.cartModal = true
    },
    addToCart(sp) {
      // 获取产品型号列表
      this.$axios.get(`/product/detail/${sp.id}`).then((resp) => {
        this.availableModels = resp.data.data; // 假设返回的型号列表字段为 models
        this.selectedProduct = sp;
        this.showModelSelectionModal = true; // 显示型号选择模态框
      }).catch(() => {
        alert("获取型号信息失败");
      });
    },
    confirmAddToCart() {
      if (!this.selectedModel) {
        alert("请选择一个型号");
        return;
      }
      this.$axios.post("/cart/add", {
        productId: this.selectedProduct.id,
        productPic: this.selectedProduct.pic,
        productName: this.selectedProduct.name,
        price: this.selectedProduct.price,
        productSkuId: this.selectedModel.id // 添加型号信息
      }).then((resp) => {
        if (resp.data.code == 200) {
          alert("添加成功");
          this.queryCart();
          this.showModelSelectionModal = false; // 隐藏型号选择模态框
          this.selectedProduct = null;
          this.selectedModel = null;
          this.availableModels = [];
        } else {
          alert("添加失败，" + resp.data.message);
        }
      }).catch(() => {
        alert("添加失败，未知原因");
      });
    },
    queryCart() {
      // 查询购物车
      this.$axios.get(
          "/cart/list"
      ).then(
          (resp) => {
            this.cart = resp.data.data
          }
      ).catch(
          () => {
            alert("获取购物车信息失败")
          }
      )
    },
    goAddr(){
      this.$router.push("/addr")
    },
    cartDelete(cartIds){
      this.$axios.post(
          "/cart/delete",
          null,
          {
            params: {
              ids: cartIds
            }
          }
      ).then(
          (resp) => {
            if (resp.data.code == 200) {
              alert("删除成功")
              this.queryCart()
            }else{
              alert("删除失败，" + resp.data.message)
            }
          }
      ).catch(
          () => {
            alert("服务器出错")
          }
      )
    },
    queryAll () {
      this.$axios.get(
          "/product/search",
      ).then(
          (resp) => {
            this.allSpData = resp.data.data
          }
      ).catch(
          () => {
            alert("错误")
          }
      )
    },
    checkout () {
      let tjorder = {
        cartIds: [],
        memberReceiveAddressId: this.selectedAddress.id
      }
      for (let i = 0; i < this.cart.length; i++) {
        tjorder.cartIds.push(this.cart[i].id)
      }
      this.$axios.post(
          "/order/generateOrder",
          tjorder
      ).then(
          (resp) => {
            console.log(resp)
          }
      ).catch(
          () => {
            console.log("失败")
          }
      )
    }
  },
  mounted(){
    // 获取商品列表
    this.queryAll()
    // 获取购物车
    this.queryCart()
    this.queryAddrs()
  }
}
</script>

<template>
  <div style="width: 100vw;height: 100vh">
    <div class="header">
      <div class="brand">卖夕夕</div>
      <div class="search-box">

      </div>
      <div class="user-info">
        <button id="logoutBtn" @click="goMyOrder">我的订单</button>
        <button id="cartBtn" @click="showCart">查看购物车</button>
        <button id="cartBtn" @click="goAddr">查看购物车</button>
      </div>
    </div>

    <div class="product-list">
      <!-- Product cards example -->
      <div class="product-card" v-for="sp in allSpData.list" :key="sp.id">
        <img :src="sp.pic" alt="Product Image" class="product-image">
        <div class="product-details">
          <h3 class="product-title">{{sp.name}}</h3>
          <p class="product-price">¥{{sp.price}}</p>
          <button @click="addToCart(sp)" class="add-to-cart">加入购物车</button>
        </div>
      </div>
      <!-- Repeat product cards as needed -->
    </div>

    <!-- Model Selection Modal -->
    <div id="modelSelectionModal" class="modal" v-if="showModelSelectionModal">
      <div class="modal-content">
        <span class="close" @click="showModelSelectionModal = false">&times;</span>
        <h2>选择型号</h2>
        <p>为 {{ selectedProduct.name }} 选择一个型号：</p>
        <select v-model="selectedModel">
          <option v-for="model in availableModels" :value="model">{{ model.spData }}</option>
        </select>
        <button @click="confirmAddToCart" class="add-to-cart">确认加入购物车</button>
      </div>
    </div>

    <!-- Shopping Cart Modal -->
    <div id="cartModal" class="modal" v-if="cartModal">
      <div class="modal-content cart-modal-content">
        <span class="close" @click="cartModal = false">&times;</span>
        <h2>购物车</h2>
        <div id="cartItems">
          <div class="cart-item" v-for="(item, index) in cart" :key="item.id">
            <img :src="item.productPic" alt="Product Image">
            <div class="cart-item-details">
              <h4 class="cart-item-title">{{item.productName}}</h4>
              <p class="cart-item-price">{{item.price}}元 x {{item.quantity}}</p>
            </div>
            <span class="cart-item-remove" @click="cartDelete(item.id)">&times;</span>
          </div>
        </div>
        <!-- Address selection -->
        <h3>选择地址</h3>
        <div>
          <select v-model="selectedAddress">
            <option v-for="(addr, index) in personAddr" :key="index" :value="addr">{{ addr.name }} - {{ addr.detailAddress }}</option>
          </select>
          <button>去编辑地址</button>
        </div>
        <div class="cart-summary">
          <h3 id="totalPrice">总价: ¥{{cartAmount}}</h3>
          <button @click="checkout()" class="checkout-btn">结算</button>
        </div>
      </div>
    </div>
  </div>
</template>


<style scoped>
*{
  text-align: left;
}
/* Global styles */
body {
  font-family: Arial, sans-serif;
  background-color: #f8f9fa;
  margin: 0;
  padding: 0;
}

/* Header styles */
.header {
  background-color: #ffffff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  padding: 10px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.brand {
  font-size: 24px;
  font-weight: bold;
  color: #007bff;
}

.search-box {
  flex-grow: 1;
  margin: 0 20px;
  display: flex;
}

.search-box input {
  flex-grow: 1;
  padding: 5px 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  outline: none;
}

.search-box button {
  padding: 5px 10px;
  border: 1px solid #ddd;
  border-left: none;
  background-color: #007bff;
  color: #ffffff;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  transition: background-color 0.2s;
}

.search-box button:hover {
  background-color: #0056b3;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info span {
  margin-right: 10px;
}

.user-info button {
  margin-left: 10px;
  padding: 8px 16px;
  border: none;
  background-color: #007bff;
  color: #ffffff;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-info button:hover {
  background-color: #0056b3;
}

/* Product list styles */
.product-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 20px;
}

.product-card {
  background-color: #ffffff;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  margin: 20px;
  width: 250px;
  transition: transform 0.2s, box-shadow 0.2s;
  cursor: pointer;
}

.product-card:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  transition: transform 0.2s;
}

.product-card:hover .product-image {
  transform: scale(1.1);
}

.product-details {
  padding: 15px;
  text-align: center;
}

.product-title {
  font-size: 18px;
  margin: 0 0 10px 0;
}

.product-price {
  font-size: 16px;
  color: #007bff;
  margin-bottom: 10px;
}

.product-card button {
  padding: 8px 16px;
  border: none;
  background-color: #28a745;
  color: #ffffff;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: block;
  margin: 10px auto 0;
}

.product-card button:hover {
  background-color: #218838;
}

/* Modal base styles */
.modal {
  position: fixed;
  z-index: 1001;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
}

.modal-content {
  background-color: #ffffff;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
  max-width: 600px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
  animation: slide-in 0.3s ease-out;
}

@keyframes slide-in {
  from {
    transform: translateY(-50%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.close {
  color: #aaaaaa;
  position: absolute;
  top: 10px;
  right: 20px;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}

.close:hover,
.close:focus {
  color: #000000;
  text-decoration: none;
}

.modal h2 {
  font-size: 24px;
  margin: 0 0 10px;
}

.modal p {
  font-size: 16px;
  color: #333333;
  margin: 10px 0;
}

.modal .product-price {
  font-size: 20px;
  color: #007bff;
  margin-bottom: 20px;
}

.modal .add-to-cart {
  padding: 10px 20px;
  border: none;
  background-color: #28a745;
  color: #ffffff;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.modal .add-to-cart:hover {
  background-color: #218838;
}

/* Shopping cart modal styles */
.cart-modal-content {
  max-width: 800px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ddd;
}

.cart-item:last-child {
  border-bottom: none;
}

.cart-item-checkbox {
  margin-right: 10px;
}

.cart-item img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 10px;
}

.cart-item-details {
  flex-grow: 1;
  margin-left: 10px;
}

.cart-item-title {
  font-size: 18px;
  margin: 0;
}

.cart-item-price {
  font-size: 16px;
  color: #007bff;
}

.cart-item-quantity {
  display: flex;
  align-items: center;
}

.cart-item-quantity input {
  width: 40px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin: 0 10px;
}

.cart-item-remove {
  color: #dc3545;
  cursor: pointer;
  transition: color 0.2s;
}

.cart-item-remove:hover {
  color: #bd2130;
}

.cart-summary {
  text-align: right;
  padding: 20px 0;
}

.cart-summary h3 {
  font-size: 24px;
  margin: 0;
}

.cart-summary button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: #ffffff;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.cart-summary button:hover {
  background-color: #0056b3;
}
/* 型号选择模态框样式 */
#modelSelectionModal .modal-content {
  max-width: 400px;
}

#modelSelectionModal select {
  width: 100%;
  padding: 10px;
  margin: 20px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}
</style>